<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="80"
    label-position="top"
  >
    <el-row class="w-full" :gutter="10">
      <el-col :span="8">
        <el-form-item label="平台" prop="platform_id">
          <SelectPlatform v-model="form.platform_id" @change="changePlatform" />
        </el-form-item>
      </el-col>
      <el-col :span="16">
        <el-form-item label="产品名称" prop="sku_cn_title">
          <el-input v-model="form.sku_cn_title" placeholder="请输入产品名称" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="输出结果语言" prop="language_id">
          <SelectLanguage
            class="w-full"
            v-model="form.language_id"
            @changeItem="changeLanguage"
          ></SelectLanguage>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="品牌">
          <SelectBrand
            class="w-full"
            v-model="form.brand_id"
            placeholder="设计品牌"
            @changeName="changeBrand"
          ></SelectBrand>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="目标人群">
          <el-input v-model="form.target_population" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <!-- <el-col :span="16">
        <el-form-item label="文案要求">
          <el-input
            v-model="form.copy_requirement"
            placeholder="若无特殊要求，则由AI 自主优化"
          />
        </el-form-item>
      </el-col> -->
      <el-col :span="8">
        <el-form-item label="规格型号">
          <el-input v-model="form.specification_model" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="生成内容" prop="generated_content">
          <el-checkbox-group v-model="form.generated_content">
            <div class="flex w-full mb-1">
              <el-checkbox label="1">标题</el-checkbox>
              <el-input
                v-model="form.generated_title_size"
                style="width: 100px"
                class="ml-[34px]"
                placeholder="字数"
                size="small"
                oninput="value=value.replace(/[^0-9]/g,'')"
              >
                <template #append>字</template>
              </el-input>
            </div>
            <div class="flex w-full mb-1">
              <el-checkbox label="2">要点</el-checkbox>
              <el-input
                v-model="form.generated_gist_size"
                style="width: 100px"
                class="ml-[34px]"
                placeholder="字数"
                size="small"
                oninput="value=value.replace(/[^0-9]/g,'')"
              >
                <template #append>字</template>
              </el-input>
              <el-input
                v-model="form.generated_gist_number"
                style="width: 100px"
                class="ml-[24px]"
                placeholder="条数"
                size="small"
                oninput="value=value.replace(/[^0-9]/g,'')"
              >
                <template #append>条</template>
              </el-input>
            </div>
            <div class="flex w-full">
              <el-checkbox label="3">商品描述</el-checkbox>
              <el-input
                v-model="form.generated_description_size"
                style="width: 100px"
                class="ml-[34px]"
                placeholder="字数"
                size="small"
                oninput="value=value.replace(/[^0-9]/g,'')"
              >
                <template #append>字</template>
              </el-input>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="提示语" prop="tips">
          <el-input
            v-model="form.tips"
            :rows="2"
            type="textarea"
            placeholder="描述该产品的特征（如形状/尺寸/材料）、功能、卖点等"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="shouldShowTitleKeyword">
        <el-form-item label="标题关键词">
          <template #label>
            <div class="flex justify-between">
              <div>标题关键词</div>
              <!-- <span
                >关键词高亮
                <el-switch class="ml-2" v-model="form.title_keyword_highlight"
              /></span> -->
            </div>
          </template>
          <el-input
            v-model="form.title_keyword"
            :rows="2"
            type="textarea"
            placeholder="一行一个，回车换行，最多五十个"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="shouldShowKeyword">
        <el-form-item label="要点关键词">
          <el-input
            v-model="form.key_word"
            :rows="2"
            type="textarea"
            placeholder="一行一个，回车换行，最多五十个；若无则默认取标题关键词"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="shouldShowDescriptionKey">
        <el-form-item label="商品描述关键词">
          <el-input
            v-model="form.description_key"
            :rows="2"
            type="textarea"
            placeholder="一行一个，回车换行，最多五十个；若无则默认取标题关键词"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="屏蔽词">
          <el-input
            v-model="form.mask_word"
            :rows="2"
            type="textarea"
            placeholder="一行一个，回车换行，最多五十个"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script name="CopyGeneration" setup>
import { factorType, shipmentMethodOptions, supplyModelOptions } from "../data.js";
import { ElMessage, ElMessageBox } from "element-plus";
import SelectPlatform from "@/components/SelectPlatform";
import SelectLanguage from "@/components/Selects/SelectLanguage";
import SelectBrand from "@/components/SelectBrand";

const shouldShowTitleKeyword = computed(() => {
  return form.value.generated_content && form.value.generated_content.includes("1");
});

const shouldShowKeyword = computed(() => {
  return form.value.generated_content && form.value.generated_content.includes("2");
});

const shouldShowDescriptionKey = computed(() => {
  return form.value.generated_content && form.value.generated_content.includes("3");
});

const data = reactive({
  form: {},
  rules: {
    sku_cn_title: [{ required: true, message: "请输入产品名称" }],
    platform_id: [{ required: true, message: "请选择平台" }],
    language_id: [{ required: true, message: "请选择语言" }],
    tips: [{ required: true, message: "请输入提示语" }],
    generated_content: [
      {
        type: "array",
        required: true,
        min: 1,
        message: "请至少选择一个生成内容",
        trigger: "change",
      },
    ],
  },
});

const { form, rules } = toRefs(data);

// 选择平台
const changePlatform = (val) => {
  form.value.platform_name = val;
};

// 选择语言
const changeLanguage = (item) => {
  form.value.language_name = item.name;
};

// 选择品牌
const changeBrand = (val) => {
  console.log(val);
  form.value.brand_name = val;
};

const formRef = ref();
const emit = defineEmits(["submit"]);
const submit = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      if (
        form.value.generated_content.includes("1") &&
        !form.value.generated_title_size
      ) {
        return ElMessage.error("请输入标题字数");
      }
      if (
        form.value.generated_content.includes("2") &&
        (!form.value.generated_gist_size || !form.value.generated_gist_number)
      ) {
        return ElMessage.error("请输入要点字数或要点条数");
      }
      if (
        form.value.generated_content.includes("3") &&
        !form.value.generated_description_size
      ) {
        return ElMessage.error("请输入商品描述字数");
      }
      const userText = getFormData();
      emit("submit", {
        type: "V3",
        userText,
      });
    }
  });
};

const getFormData = () => {
  const preamble = `你是一位资深${form.value.platform_name}运营经理，\n请根据以下格式和信息，帮我生成${form.value.platform_name}平台`;

  const selectedContent = form.value.generated_content;
  const contentTypes = {
    1: "标题",
    2: "要点",
    3: "商品描述",
  };

  let preambleContentTypes = [];
  selectedContent.forEach((contentType) => {
    if (contentTypes[contentType]) {
      preambleContentTypes.push(contentTypes[contentType]);
    }
  });

  const preambleWithContentTypes = preamble + preambleContentTypes.join("、") + "；\n";
  const dataParts = [preambleWithContentTypes];

  // 格式
  const formatInfoParts = [];
  let formatIndex = 1; // 初始化序号
  if (form.value.generated_content.includes("1")) {
    formatInfoParts.push(`${formatIndex++}、标题`);
    formatInfoParts.push(`${formatIndex++}、标题翻译: 标题内容翻译成中文`);
  }
  if (form.value.generated_content.includes("2")) {
    formatInfoParts.push(`${formatIndex++}、要点`);
    formatInfoParts.push(`${formatIndex++}、要点翻译: 要点内容翻译成中文`);
  }
  if (form.value.generated_content.includes("3")) {
    formatInfoParts.push(`${formatIndex++}、商品描述`);
    formatInfoParts.push(`${formatIndex++}、商品描述：商品描述内容翻译成中文`);
  }
  formatInfoParts.push(`${formatIndex++}、文案输出原因说明`);

  // 如果 productInfoParts 不为空，则将其添加到 dataParts 中
  if (formatInfoParts.length > 0) {
    dataParts.push("格式：");
    dataParts.push(formatInfoParts.join("\n"));
  }

  // 相关信息及要求
  const relevantInfoParts = [];
  let index = 1; // 初始化序号

  // 内容输出语言
  if (form.value.language_id) {
    relevantInfoParts.push(`${index++}、内容输出语言：${form.value.language_name}`);
  }

  // 产品名称
  if (form.value.sku_cn_title) {
    relevantInfoParts.push(`${index++}、产品名称：${form.value.sku_cn_title}`);
  }

  // 目标人群
  if (form.value.target_population) {
    relevantInfoParts.push(`${index++}、目标人群：${form.value.target_population}`);
  }

  // 品牌
  if (form.value.brand_id) {
    relevantInfoParts.push(`${index++}、品牌：${form.value.brand_name}`);
  }

  // 型号
  if (form.value.specification_model) {
    relevantInfoParts.push(`${index++}、型号：${form.value.specification_model}`);
  }

  // 提示语
  if (form.value.tips) {
    const tipsArray = form.value.tips
      .split("\n")
      .map((tip) => tip.trim())
      .filter((tip) => tip);
    relevantInfoParts.push(`${index++}、提示语：${tipsArray.join("、")}`);
  }

  // 标题字数
  if (form.value.generated_content.includes("1") && form.value.generated_title_size) {
    relevantInfoParts.push(`${index++}、标题字数：${form.value.generated_title_size}`);
  }

  // 标题关键词
  if (form.value.generated_content.includes("1") && form.value.title_keyword) {
    const titleKeywordArray = form.value.title_keyword
      .split("\n")
      .map((tip) => tip.trim())
      .filter((tip) => tip);
    relevantInfoParts.push(`${index++}、标题关键词：${titleKeywordArray.join("、")}`);
  }

  // 内容字数
  if (form.value.generated_content.includes("2") && form.value.generated_gist_size) {
    relevantInfoParts.push(`${index++}、内容字数：${form.value.generated_gist_size}`);
  }

  // 内容条数
  if (form.value.generated_content.includes("2") && form.value.generated_gist_number) {
    relevantInfoParts.push(`${index++}、内容条数：${form.value.generated_gist_number}`);
  }

  // 内容关键词
  if (form.value.key_word) {
    const keyWordArray = form.value.key_word
      .split("\n")
      .map((tip) => tip.trim())
      .filter((tip) => tip);
    relevantInfoParts.push(`${index++}、内容关键词：${keyWordArray.join("、")}`);
  }

  // 商品描述字数
  if (
    form.value.generated_content.includes("3") &&
    form.value.generated_description_size
  ) {
    relevantInfoParts.push(
      `${index++}、商品描述字数：${form.value.generated_description_size}`
    );
  }

  // 商品描述关键词
  if (form.value.description_key) {
    const descriptionKeyArray = form.value.description_key
      .split("\n")
      .map((tip) => tip.trim())
      .filter((tip) => tip);
    relevantInfoParts.push(
      `${index++}、商品描述关键词：${descriptionKeyArray.join("、")}`
    );
  }

  // 文案要求
  if (form.value.copy_requirement) {
    relevantInfoParts.push(`${index++}、文案要求：${form.value.copy_requirement}`);
  }

  // 屏蔽词
  if (form.value.mask_word) {
    const maskWordArray = form.value.mask_word
      .split("\n")
      .map((tip) => tip.trim())
      .filter((tip) => tip);
    relevantInfoParts.push(`${index++}、屏蔽词：${maskWordArray.join("、")}`);
  }
  // relevantInfoParts.push(`${index++}、文案要求：突出关键词和目标人群`);
  if (form.value.title_keyword_highlight) {
    relevantInfoParts.push(
      `显示要求：将${preambleContentTypes.join(
        "、"
      )}维护的关键词，在输出内容中关键词背景色改为黄色显示`
    );
  }
  // 如果 productInfoParts 不为空，则将其添加到 dataParts 中
  if (relevantInfoParts.length > 0) {
    dataParts.push("相关信息及要求：");
    dataParts.push(relevantInfoParts.join("\n"));
  }

  // 最终拼接成完整的字符串
  const finalData = dataParts.join("\n");

  return finalData; // 如果有需要返回数据的地方
};

const reset = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  init();
};

const init = () => {
  form.value = {
    language_id: 2,
    language_name: "英文",
    generated_content: ["1"],
    generated_title_size: 200,
    generated_gist_size: 500,
    generated_gist_number: 5,
    generated_description_size: 500,
    title_keyword_highlight: true,
  };
};

onMounted(() => {
  init();
});

defineExpose({ submit, reset });
</script>
<style lang="scss" scoped></style>
